import {
    getPlayerData,
    storagePlayerData,
    ensureGroupAndPlayerExist,
    formatCurrency,
    getConfig
} from "../function/function.js";
import lodash from 'lodash';
import { checkPermission } from "../function/function.js";

export class SlaveArena extends plugin {
    constructor() {
        super({
            name: '[Sm]奴隶竞技场',
            dsc: '让奴隶在竞技场战斗',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]决斗\s*(\d+)\s*(\d+)$/, fnc: 'battle' }
            ]
        })
    }

    async battle(e) {
        if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 确保群组和玩家数据存在
        ensureGroupAndPlayerExist(ID[1], ID[0]);

        const matches = e.msg.match(/^[#\/]决斗\s*(\d+)\s*(\d+)$/);
        const slave1 = parseInt(matches[1]);
        const slave2 = parseInt(matches[2]);

        if (slave1 === slave2) {
            return e.reply(['不能让同一个奴隶自己决斗']);
        }

        try {
            const userData = await getPlayerData(ID[1], ID[0]);
            if (!userData.slave.includes(slave1)) {
                return e.reply(['你不是参战奴隶的主人']);
            }

            const config = getConfig();
            const currentTime = Math.floor(Date.now() / 1000);

            // 检查冷却时间
            if (!checkPermission(e) && userData.lastBattleTime && currentTime - userData.lastBattleTime < config.arena.cooldown) {
                const remainingTime = config.arena.cooldown - (currentTime - userData.lastBattleTime);
                const hours = Math.floor(remainingTime / 3600);
                const minutes = Math.floor((remainingTime % 3600) / 60);
                return e.reply([`决斗冷却中，剩余时间：${hours}小时${minutes}分钟`]);
            }

            // 检查参赛费用
            if (userData.currency < config.arena.entryFee) {
                return e.reply([`参加决斗需要${config.arena.entryFee}金币，你的余额不足`]);
            }

            const slave1Data = await getPlayerData(ID[1], slave1);
            const slave2Data = await getPlayerData(ID[1], slave2);
            const memberMap = await Bot.pickGroup(ID[1]).getMemberMap();

            // 添加战斗过程描述
            const battleProcess = this.generateBattleProcess(
                memberMap.get(slave1).nickname,
                memberMap.get(slave2).nickname,
                slave1Data.value,
                slave2Data.value
            );

            // 计算战斗结果
            const result = this.calculateBattleResult(slave1Data, slave2Data);
            const winner = result ? slave1 : slave2;
            const loser = result ? slave2 : slave1;
            const winnerData = result ? slave1Data : slave2Data;
            const loserData = result ? slave2Data : slave1Data;

            // 计算奖励和惩罚
            const reward = Math.floor(config.arena.entryFee * config.arena.rewardRate);
            const valueIncrease = Math.floor(winnerData.value * config.arena.valueBonus);
            const valueDecrease = Math.floor(loserData.value * 0.05); // 失败者损失5%身价

            // 更新数据
            winnerData.value = formatCurrency(winnerData.value + valueIncrease);
            loserData.value = formatCurrency(Math.max(100, loserData.value - valueDecrease));
            userData.currency = formatCurrency(userData.currency - config.arena.entryFee + reward);
            userData.lastBattleTime = currentTime;

            // 记录战绩
            if (!userData.battleStats) userData.battleStats = { wins: 0, losses: 0 };
            userData.battleStats.wins++;

            storagePlayerData(ID[1], winner, winnerData);
            storagePlayerData(ID[1], loser, loserData);
            storagePlayerData(ID[1], ID[0], userData);

            return e.reply([
                segment.at(ID[0]), '\n',
                ...battleProcess,
                `\n决斗结束！${memberMap.get(winner).nickname}获胜！\n`,
                `获得${reward}金币奖励\n`,
                `${memberMap.get(winner).nickname}身价提升${valueIncrease}，现在为${winnerData.value}金币\n`,
                `${memberMap.get(loser).nickname}身价下降${valueDecrease}，现在为${loserData.value}金币\n`,
                `你的战绩: ${userData.battleStats.wins}胜 ${userData.battleStats.losses}负`
            ]);
        } catch (error) {
            logger.error('处理决斗请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试']);
        }
    }

    calculateBattleResult(slave1Data, slave2Data) {
        // 基础胜率为50%
        let slave1WinRate = 0.5;

        // 根据价值差异调整胜率
        const valueDiff = slave1Data.value - slave2Data.value;
        const valueBonus = Math.min(0.3, Math.abs(valueDiff) / Math.max(slave1Data.value, slave2Data.value) * 0.5);

        if (valueDiff > 0) {
            slave1WinRate += valueBonus;
        } else {
            slave1WinRate -= valueBonus;
        }

        // 返回战斗结果
        return Math.random() < slave1WinRate;
    }

    // 生成战斗过程描述
    generateBattleProcess(name1, name2, value1, value2) {
        const actions = [
            `${name1}使出浑身解数`,
            `${name2}奋力反击`,
            `${name1}展开猛攻`,
            `${name2}寻找破绽`,
            `${name1}气势如虹`,
            `${name2}毫不示弱`
        ];

        const process = [];
        const rounds = Math.floor(Math.random() * 2) + 2; // 2-3个回合

        for (let i = 0; i < rounds; i++) {
            process.push(lodash.sample(actions));
        }

        return process;
    }
} 